package com.abigdreamer.wordpress.newspider;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

/**
 * 以 dict.cn 网站为例的爬虫
 * 
 * @author Winter Lau
 */
public class HtmlSpider {

	protected HttpClient client = new DefaultHttpClient();
	
	public HttpClient getclient(){
		return client;
	}

	/**
	 * 抓取网页
	 * 
	 * @param url
	 * @throws IOException
	 */
	public String get(String url) throws IOException {
		HttpGet get = new HttpGet(url);
		HttpResponse response = client.execute(get);
		// System.out.println(response.getStatusLine());
		HttpEntity entity = response.getEntity();

		BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "utf-8"));

		return IOUtils.toString(br);
	}


	/**
	 * 执行登录过程
	 * 
	 * @param user
	 * @param pwd
	 * @param debug
	 * @throws IOException
	 */
	public void login(LoginFormInfo loginFormInfo, boolean debug) throws IOException {

		HttpPost post = new HttpPost(loginFormInfo.getUrl());
		post.setHeader("User-Agent",
				"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3");

		// 登录表单的信息
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();

		for (String paramName : loginFormInfo.getParams().keySet()) {
			qparams.add(new BasicNameValuePair(paramName, loginFormInfo.getParams().get(paramName)));
		}

		UrlEncodedFormEntity params = new UrlEncodedFormEntity(qparams, "UTF-8");
		post.setEntity(params);

		// Execute the request
		HttpResponse response = client.execute(post);

		if (debug) {
			// Examine the response status
			// System.out.println(response.getStatusLine());

			// Get hold of the response entity
			HttpEntity entity = response.getEntity();

			dump(entity);
		}
		post.abort();
	}

	/**
	 * 打印页面
	 * 
	 * @param entity
	 * @throws IOException
	 */
	private static void dump(HttpEntity entity) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "utf-8"));

		System.out.println(IOUtils.toString(br));
	}

}
